package net.topicopedia.servlets.topics;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class GetTopicsServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("Creating new todo ");
		    
		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.setContentType("text/plain");
		 
		String output = "[";
		
		String tags = req.getParameter("tags");
		
		List<String> searchTags = Arrays.asList(tags.split(", "));
		
		if ( searchTags.isEmpty() )
		{
			output = "[]";
			resp.getWriter().println( output );
			return;
		}
		
		List<String> topicKeys = new ArrayList<String>();
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		for ( String string : searchTags )
		{
			Key tagKey = KeyFactory.createKey("Tag", (Long) Long.parseLong(string) );
			Entity tag = null;
			try {
				tag = datastore.get(tagKey);
			} catch (EntityNotFoundException e) {
				// TODO Auto-generated catch block
				System.out.println ( e.getMessage() );
			}
			if ( tag != null )
			{
				JSONObject tagTopicsObject = null;
				try {
					String tagTopicsTextString = ( (Text) tag.getProperty("topics") ).getValue();
					if ( tagTopicsTextString == null || tagTopicsTextString == "" ){
						tagTopicsObject = null;
					} else {
						tagTopicsObject = new JSONObject( tagTopicsTextString );
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					System.out.println ( e.getMessage() );
				}
				if (tagTopicsObject != null)
				{
					JSONArray tagTopicsArray=null;
					try {
						tagTopicsArray = tagTopicsObject.getJSONArray("topics");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						System.out.println ( e.getMessage() );
					}
					if( tagTopicsArray != null )
					{
						for ( int t=0; t< tagTopicsArray.length(); t++)
						{
							JSONObject tagtopic = null;
							try {
								tagtopic = tagTopicsArray.getJSONObject(t);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								System.out.println ( e.getMessage() );
							}
							if ( tagtopic != null )
							{
								String tagTopickey = null;
								try {
									tagTopickey = tagtopic.getString("uuid");
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									System.out.println ( e.getMessage() );
								}
								if ( tagTopickey != null )
								{
									Boolean add = true;
									for ( String keyString : topicKeys )
									{
										if ( keyString.equalsIgnoreCase(tagTopickey) )
										{
											add = false;
										}
									}
									if ( add )
									{
										topicKeys.add(tagTopickey);
									}
								}	
							}
						}
					}
				}
				
			}
			
		}
		
		output = "[";
		
		for ( String string : topicKeys )
		{
			Key topicKey = KeyFactory.createKey("Topic", (Long) Long.parseLong(string) );
			Entity topic = null;
			try {
				topic = datastore.get(topicKey);
			} catch (EntityNotFoundException e) {
				// TODO Auto-generated catch block
				System.out.println ( e.getMessage() );
			}
			
			if ( topic != null )
			{
				String storedUuid = topic.getKey().getId() + "";
				String storedTitle = (String) topic.getProperty("title");
				String storedDescriptor = (String) topic.getProperty("descriptor");
				String storedCategory = topic.getProperty("category")+"";
				
				Text storedTags = (Text) topic.getProperty("tags");
				
				Text storedItems = (Text) topic.getProperty("items");
				Text storedLinks = (Text) topic.getProperty("links");
				
				if ( output.length() > 1 )
				{
					output += ", ";
				}
				
				output += "{\"uuid\": " + storedUuid;
				output += ", \"title\": " + "\"" + storedTitle + "\"";
				output += ", \"descriptor\": " + "\"" + storedDescriptor + "\"";
				output += ", \"category\": " + storedCategory;
				output += ", " + storedTags.getValue() + "\"";
				output += ", \"items\": " + storedItems.getValue();
				output += ", \"links\": " + storedLinks.getValue();
				output += "}";
			}
			
		}
		
		output += "]";
		
		resp.getWriter().println( output );
		
	}
}
 